import { Provide, Inject, Config } from '@midwayjs/core';

import { JwtService } from '@midwayjs/jwt';
import { User } from '../entity/user.entity';
import {
  AdminLoginReq,
  AdminLoginRes,
  Jwt,
  Pagination,
  UpdateUserReq,
} from '../model';
import { Backstage } from '../entity/backstage.entity';
@Provide()
export class UserService {
  @Inject()
  jwtService: JwtService;
  @Config('jwt')
  jwt: Jwt;
  async getToken(sign: string) {
    return await this.jwtService.sign({ sign });
  }
  async createAccount(phone: number) {
    const result = await User.findOrCreate({
      where: { phone },
      defaults: {
        phone,
      },
      attributes: { exclude: ['createdAt'] },
    });
    return result[0];
  }
  async adminLogin(req: AdminLoginReq): Promise<AdminLoginRes> {
    const result: AdminLoginRes = await Backstage.findOne({
      where: {
        account: req.account,
        pwd: req.pwd,
      },
      attributes: { exclude: ['createdAt', 'updatedAt'] },
    });
    return result;
  }
  async getAdminToken(req: AdminLoginRes) {
    const sign = {
      id: req.id,
      account: req.account,
    };
    const token = await this.jwtService.sign({ sign }, this.jwt.adminSecret);
    return `Bear_${token}`;
  }

  async updateUser(id: number, req: UpdateUserReq) {
    const result = await User.update(
      {
        ...req
      },
      {
        where: {
          id,
        },
      }
    );
    return result;
  }

  async userDetails(id: number) {
    return await User.findOne({
      where: {
        id,
      },
    });
  }

  async getList(req: Pagination) {
    const { count, rows } = await User.findAndCountAll({
      limit: req.pageSize,
      offset: (req.pageNo - 1) * req.pageSize,
      attributes: { exclude: ['createdAt', 'updatedAt'] },
      order:[['id','DESC']]
    });
    rows.map(item => {
      const keys = Object.keys(item.dataValues);
      keys.map(key => {
        if (item.dataValues[key] === null) {
          item.dataValues[key] = '';
        }
      });
    });
    return {
      count,
      rows,
    };
  }
}
